<template>
  <el-dialog title="编辑用户权限" v-model="dialogVisible" width="500px" @close="emit('submit')">
    <el-form label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="username" disabled></el-input>
      </el-form-item>

      <el-form-item label="角色列表">
        <el-checkbox-group v-model="selectedRoles">
          <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
            {{ role.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updateRoles">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { getRoles, getUserRole, updateUserRole } from '../../api/user'
const emit = defineEmits(['submit'])
const dialogVisible = ref(false)
const allRoles = ref([]) // 所有角色
const selectedRoles = ref([]) // 已选角色
const currentUserId = ref(null)
const username = ref(null)

// 打开弹窗时获取所有角色 & 用户已有角色
const openDialog = async (row) => {
  dialogVisible.value = true
  currentUserId.value = row.id
  username.value = row.username

  try {
    // 先获取所有角色
    const res = await getRoles()
    if (res.status === 200 || res.status === 201) {
      allRoles.value = res.data.data
    }

    // 再获取当前用户的角色
    const res2 = await getUserRole(currentUserId.value)
    if (res2.status === 200 || res2.status === 201) {
      selectedRoles.value = res2.data.data
    }
  } catch (error) {
    console.error('获取角色信息失败', error)
  }
}

// 更新用户角色
const updateRoles = async () => {
  if (!selectedRoles.value.length) {
    ElMessage.error('请选择角色')
    return
  }
  try {
    const roleIds = selectedRoles.value.map(Number)

    const res = await updateUserRole(currentUserId.value, roleIds)

    if (res.status === 200 || res.status === 201) {
      ElMessage.success('角色更新成功')
      resetDialog()
    } else {
      ElMessage.error('角色更新失败')
    }
  } catch (error) {
    console.error('更新角色失败', error)
    ElMessage.error('更新角色失败')
  }
}

// // 关闭弹窗时重置数据
const resetDialog = () => {
  currentUserId.value = null
  selectedRoles.value = []
  dialogVisible.value = false
}

defineExpose({ openDialog, resetDialog })
</script>
<style lang="scss" scoped>
</style>
